#include <am.h>
#include <riscv/riscv.h>
#include <klib.h>

static Context* (*user_handler)(Event, Context*) = NULL;

Context* __am_irq_handle(Context *c) {
  if (user_handler) {
    Event ev = {0};

    switch (c->mcause) {
	  case 0xb: ev.event = EVENT_YIELD,c->mepc+=4;break;
      default: ev.event = EVENT_ERROR; break;
    }
    c = user_handler(ev, c);
    assert(c != NULL);
  }

  return c;
}

extern void __am_asm_trap(void);

bool cte_init(Context*(*handler)(Event, Context*)) {
  // initialize exception entry
  asm volatile("csrw mtvec, %0" : : "r"(__am_asm_trap));

  // register event handler
  user_handler = handler;

  return true;
}

//在内存中初始化一个区域ctx，以栈形式存储
Context *kcontext(Area kstack, void (*entry)(void *), void *arg) {
  //return NULL;
	Context* ctx = kstack.end - sizeof(Context);//指向内核上下文的起始 
	ctx->mepc = (uintptr_t)entry;//yield_os中，这里指向一个测试函数f，使得yield进行mret后，不从原来的mepc+4返回，而是新的entry返回
	ctx->gpr[10] = (uintptr_t)arg;//gpr[10]==$a0
	ctx->mstatus = 0x1800;//使difftest不报错
	return ctx;

}

void yield() {
#ifdef __riscv_e
  asm volatile("li a5, -1; ecall");
#else
  asm volatile("li a7, -1; ecall");
#endif
}

bool ienabled() {
  return false;
}

void iset(bool enable) {
}
